<?
session_start();
function DisplayTeam($teamnum)
{
	?>
    <h1 style="text-align:center;">Viewing data for Team <? echo $teamnum;?></h1>
    <?
	$datatable=GetDataTable();
	$result=mysql_query("SELECT * FROM `" . $datatable . "` WHERE Team='" . $teamnum . "' AND Regional='".$_SESSION['regional']."';");
	if (!$result) {
    die('Invalid query: ' . mysql_error());
	}
	if(mysql_num_rows($result)==0)
	{
		echo "<p style=\"color:red;\">There doesnt seem to be anything there...</p>";
	}
	else
	{
		echo "<table border=\"2\">\n";
		echo "<tr class=\"tableheader\">\n";
		for($i=1;$i<mysql_num_fields($result);$i++)
		{
			$fieldname=mysql_field_name($result,$i);
			if($fieldname=="Regional")
			{
				continue;
			}
			echo "<td>";
			echo "<font>" . $fieldname . "</font>";
			echo "</td>\n";
		}
		echo "</tr>\n";
	while($row=mysql_fetch_row($result))
	{
		echo "<tr>\n";
		for($i=1;$i<mysql_num_fields($result);$i++)
		{
			$fieldvalue=$row[$i];
			$fieldname=mysql_field_name($result,$i);
			if($fieldname=="Regional")
			{
				continue;
			}
			echo "<td>";
			if($fieldname=="Match")
			{
				echo "<a href=\"view.php?match=" . $fieldvalue . "\">" . $fieldvalue . "</a>";
			}
			else if($fieldname=="Team")
			{
				echo "<a href=\"view.php?team=" . $fieldvalue . "\">" . $fieldvalue . "</a>";
			}
			else
			{
				echo "" . $fieldvalue . "";
			}
			echo "</td>\n";
		}
		echo "</tr>\n";
	}
	echo "</table>";
	}
	$cols=EnumerateColumnNames();
	$numcols=count($cols);
	$eventid=GetEventid(GetDataTable());
	$limit=0;
	$text=array();
	$field=array();
	for($i=1;$i<=$numcols;$i++)
	{
		#determine whether or not the column needs to be charted
		$q="SELECT * FROM eventvars WHERE `eventid`='" . $eventid . "' AND `fieldname`='" . $cols[$i] . "'";
		#echo $q."---";
		$e=mysql_query($q) or die(mysql_error());
		#$r=GetEventVars($eventid,$cols[$i]);
		#$table=GetEventVars($eventid,$cols[$i]);
		$r=mysql_fetch_array($e);
		if($r['chart_match']=='1')
		{
			array_push($text,$cols[$i]);
			array_push($field,$cols[$i]);
			$limit++;
		}
		#echo "chart_chart:".$r['chart_chart']." - ".$cols[$i];
		#echo "test\n";
	}
	#DisplayChartsTeam($limit, $field, $container, $title, $text,$team)
	DisplayChartsTeam($limit,$field,"team_chart_container",("Team Data for Team ".$teamnum),$text,"Points",$teamnum);
}

function DisplayMatch($matchnum)
{
	?>
    <h1 style="text-align:center;">Viewing data for Match <? echo $matchnum;?></h1>
    <?
	$numteams=GetNumTeamsMatch();
	$datatable=GetDataTable();
	$result=mysql_query("SELECT * FROM `" . $datatable . "` WHERE `Match`='" . $matchnum . "' AND Regional='".$_SESSION['regional']."' LIMIT ".$numteams.";");
	if (!$result) {
    die('Invalid query: ' . mysql_error());
	}
	if(mysql_num_rows($result)==0)
	{
		echo "<p style=\"color:red;\">There doesnt seem to be anything there...</p>";
	}
	else
	{
		echo "<table border=\"2\">\n";
		echo "<tr class=\"tableheader\">\n";
		for($i=1;$i<mysql_num_fields($result);$i++)
		{
			$fieldname=mysql_field_name($result,$i);
			if($fieldname=="Regional")
			{
				continue;
			}
			echo "<td>";
			echo "<font>" . $fieldname . "</font>";
			echo "</td>\n";
		}
		echo "</tr>\n";
	while($row=mysql_fetch_row($result))
	{
		echo "<tr>\n";
		for($i=1;$i<mysql_num_fields($result);$i++)
		{
			$fieldvalue=$row[$i];
			$fieldname=mysql_field_name($result,$i);
			if($fieldname=="Regional")
			{
				continue;
			}
			echo "<td>";
			if($fieldname=="Match")
			{
				echo "<a href=\"view.php?match=" . $fieldvalue . "\">" . $fieldvalue . "</a>";
			}
			else if($fieldname=="Team")
			{
				echo "<a href=\"view.php?team=" . $fieldvalue . "\">" . $fieldvalue . "</a>";
			}
			else
			{
				echo "" . $fieldvalue . "";
			}
			echo "</td>\n";
		}
		echo "</tr>\n";
	}
	echo "</table>";
	}
	$cols=EnumerateColumnNames();
	$numcols=count($cols);
	$eventid=GetEventid(GetDataTable());
	$limit=0;
	$text=array();
	$field=array();
	for($i=1;$i<=$numcols;$i++)
	{
		#determine whether or not the column needs to be charted
		$q="SELECT * FROM eventvars WHERE `eventid`='" . $eventid . "' AND `fieldname`='" . $cols[$i] . "'";
		#echo $q."---";
		$e=mysql_query($q) or die(mysql_error());
		#$r=GetEventVars($eventid,$cols[$i]);
		#$table=GetEventVars($eventid,$cols[$i]);
		$r=mysql_fetch_array($e);
		if($r['chart_match']=='1')
		{
			array_push($text,$cols[$i]);
			array_push($field,$cols[$i]);
			$limit++;
		}
		#echo "chart_chart:".$r['chart_chart']." - ".$cols[$i];
		#echo "test\n";
	}
	#function DisplayChartsMatch($limit, $field[], $container, $title, $text[],$yaxis)
	DisplayChartsMatch($limit,$field,"match_chart_container",("Match ".$matchnum),$text,"Points",$matchnum);
}

function DisplayAll($repeat)
{
	
	/*
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script>
 $(document).ready(function() {
 	 $("#responsecontainer").load("response.php");
   var refreshId = setInterval(function() {
      $("#responsecontainer").load('response.php?randval='+ Math.random());
   }, 9000);
   $.ajaxSetup({ cache: false });
});
</script>
	
	*/
	?>
    <h1 align="center">Displaying All Data for <? echo $_SESSION['regional'] ?> Regional</h1>
    <script src="sorttable.js"></script>
    <?
	$datatable=GetDataTable();
	$result=mysql_query("SELECT * FROM `" . $datatable . "`  WHERE Regional='".$_SESSION['regional']."' ORDER BY `Match` ASC");
	if (!$result) {
    die('Invalid query: ' . mysql_error());
	}
	if(mysql_num_rows($result)==0)
	{
		echo "<p style=\"color:red;\">There doesnt seem to be anything there...</p>";
	}
	else
	{
		echo "<div id=\"viewcontent\" style=\"vertical-align:middle;\">\n";
		echo "<table class=\"sortable\" border=\"2\">\n";
		echo "<tr class=\"tableheader\">\n";
		for($i=1;$i<mysql_num_fields($result);$i++)
		{
			$fieldname=mysql_field_name($result,$i);
			if($fieldname=="Regional")
			{
				continue;
			}
			echo "<td>\n";
			echo "<font style='font-weight:bold;'>" . $fieldname . "</font>\n";
			echo "</td>\n";
		}
		echo "</tr>\n";
	$rep=0;
	while($row=mysql_fetch_row($result))
	{
		/*if($rep%6==0 & $rep!=0)
		{
			echo "<tr class=\"tableheader\">\n";
		for($i=1;$i<mysql_num_fields($result);$i++)
		{
			$fieldname=mysql_field_name($result,$i);
			if($fieldname=="Regional")
			{
				continue;
			}
			echo "<td>\n";
			echo "<font style='font-weight:bold;'>" . $fieldname . "</font>\n";
			echo "</td>\n";
		}
		echo "</tr>\n";
		}*/
		echo "<tr>\n";
		for($i=1;$i<mysql_num_fields($result);$i++)
		{
			$fieldvalue=$row[$i];
			$fieldname=mysql_field_name($result,$i);
			if($fieldname=="Regional")
			{
				continue;
			}
			echo "<td>";
			if($fieldname=="Match")
			{
				echo "<a href=\"view.php?match=" . $fieldvalue . "\">" . $fieldvalue . "</a>";
			}
			else if($fieldname=="Team")
			{
				echo "<a href=\"view.php?team=" . $fieldvalue . "\">" . $fieldvalue . "</a>";
			}
			else
			{
				echo "" . $fieldvalue . "";
			}
			echo "</td>\n";
		}
		echo "</tr>\n";
		$rep++;
	}
	echo "</table>";
	echo "</div>";
	}
}

function EnumerateColumnNames()
{
	$datatable=GetDataTable();
	//echo $datatable;
	$query ="DESCRIBE `" . $datatable . "`";
	$result = mysql_query($query) or die(mysql_error());
	$j=1;

	while($i = mysql_fetch_assoc($result))
	{
		if($i['Field']=="Regional")
		{
			continue;
		}
		$array[$j]=$i['Field'];
		$j++;
	}
	//print_r($array);
	return $array;
}

function DisplaySpyderRank($limit)
{
	$q="SELECT Team FROM teams WHERE Datatable='".$_SESSION['datatable']."' AND Regional='".$_SESSION['regional']."'";
	$r=mysql_query($q)or die(mysql_error());
	$cols=EnumerateColumnNames();
	$numcols=count($cols);
	$eventid=Geteventid(GetDataTable());
	$Teams=array();
	?>
	<script src="sorttable.js"></script>
    <h1>SpyderRank, A Team Ranking by Offensive Power.</h1>
    <table class="sortable" border="2" cellspacing="2" cellpadding="2">
    <tr class="tableheader">
    <td>Rank</td>
    <td>Team</td>
    <td>Spyder Points</td>
	<?
	for($p=1;$p<=$numcols;$p++)
			{		//for the columns, get the event variables
				$q1="SELECT * FROM eventvars WHERE `eventid`='" . $eventid . "' AND `fieldname`='" . $cols[$p] . "'";
				$e1=mysql_query($q1) or die(mysql_error());
				$s1=mysql_fetch_array($e1);
				if($s1['rank_display']=='1')
				{//detect if rank display is enabled for said column.  if so, display else, continue.
					echo "<td>";
					//display the table header.
					echo $cols[$p];
					echo "</td>";

				}
			}
	?>
    </tr>
    <?
	while($row=mysql_fetch_array($r))
	{
		$TeamRank=0;
		for($i=1;$i<=$numcols;$i++)
		{
			$q="SELECT * FROM eventvars WHERE `eventid`='" . $eventid . "' AND `fieldname`='" . $cols[$i] . "'";
			$e=mysql_query($q) or die(mysql_error());
			$s=mysql_fetch_array($e);
			if($s['rank_predict']=='1')
			{
				$TeamRank=$TeamRank+GetFieldRanking($cols[$i],$row['Team']);
			}
		}
		$Teams[$row['Team']] = round($TeamRank,3);
	}
	arsort($Teams);
	$i=1;
	foreach($Teams as $key => $value) {
		if($i<=$limit){
			echo "<tr>";
			echo "<td>";
			echo $i;
			echo "</td>";
			echo "<td>";
			echo "<a href=\"view.php?team=".$key."\">Team ".$key."</a>";
			echo "</td>";
			echo "<td>";
			echo $value;
			echo "</td>";
			for($p=1;$p<=$numcols;$p++)
			{		//for the columns, get the event variables
				$q1="SELECT * FROM eventvars WHERE `eventid`='" . $eventid . "' AND `fieldname`='" . $cols[$p] . "'";
				$e1=mysql_query($q1) or die(mysql_error());
				$s1=mysql_fetch_array($e1);
				if($s1['rank_display']=='1')
				{//detect if rank display is enabled for said column.  if so, display else, continue.
					$qd="SELECT sum(`".$cols[$p]."`) FROM `".$_SESSION['datatable']."` WHERE Team='".$key."' AND regional='".$_SESSION['regional']."';";
					$rd=mysql_query($qd) or die(mysql_error());
					$ra=mysql_fetch_array($rd);
					echo "<td>";
					//display the content from the query ran above.
					echo $ra['sum(`'.$cols[$p].'`)'];
					echo "</td>";

				}
			}
			echo "</tr>\n";
			$i++;
		}
	}
}

function MatchPredictorDisplay()
{
	$numteams=GetNumTeamsMatch();
	?>
    <h1>Match Predictor</h1><br />
    <form action="view.php" method="get">
    <table border="2">
    <tr class="tableheader">
    <td>Red Team</td>
    <td>Blue Team</td>
    </tr>
    <?
	for($i=1;$i<=$numteams/2;$i++)
	{
		if($numteams=6)
		{
			echo "<tr>";
			echo "<td><input type=\"text\" name=\"competitor_".$i."\"/></td>";
			echo "<td><input type=\"text\" name=\"competitor_".($i+3)."\"/></td>";
			echo "<tr>\n";
		}
		else
		{
			echo "<tr>";
			echo "<td><input type=\"text\" name=\"competitor_".$i."\"/></td>";
			echo "<td><input type=\"text\" name=\"competitor_".($i+2)."\"/></td>";
			echo "<tr>\n";
		}
	}
	?>
    </table>
    <input type="hidden" name="predictor" value="1" />
    <input type="submit" value="GO!" />
    </form>
    
    <?
}

function PredictMatch($competitors)
{
	?> <h1>Predicted Match Results</h1> <?
	$cols=EnumerateColumnNames();
	$numcols=count($cols);
	$eventid=Geteventid(GetDataTable());
	$Teams=array();
	$numteams=count($competitors);
	for($p=1;$p<=$numteams;$p++)
	{
		$R1Rank=0;
		for($i=1;$i<=$numcols;$i++)
		{
			$q="SELECT * FROM eventvars WHERE `eventid`='" . $eventid . "' AND `fieldname`='" . $cols[$i] . "'";
			$e=mysql_query($q) or die(mysql_error());
			$s=mysql_fetch_array($e);
			if($s['rank_predict']=='1')
			{
				$frank=GetFieldRanking($cols[$i],$_GET['competitor_'.$p]);
				$R1Rank=$R1Rank+$frank;
			}
		}
		$Teams[$p] = round($R1Rank,3);
	}
	echo "<table border=\"2\" cellpadding=\"2\" cellspacing=\"2\">";
	echo "<tr class=\"tableheader\">";
	echo "<td>Red</td>";
	echo "<td></td>";
	echo "<td>Blue</td>";
	echo "<td></td>";
	echo "</tr>";
	echo "<tr>";
	echo "<td>Team</td>";
	echo "<td>Score</td>";
	echo "<td>Team</td>";
	echo "<td>Score</td>";
	echo "</tr>";
	$totalred=0;
	$totalblue=0;
	for($i=1;$i<=($numteams/2);$i++)
	{
		if($numteams=6)
		{
			$red=$Teams[$i];
			$blue=$Teams[$i+3];
			$totalred=$totalred+$red;
			$totalblue=$totalblue+$blue;
			echo "<tr>";
			echo "<td>".$competitors[$i]."</td>";
			echo "<td>".$red."</td>";
			echo "<td>".$competitors[$i+3]."</td>";
			echo "<td>".$blue."</td>";
			echo "</tr>";
		}
		else
		{
			$red=$Teams[$i];
			$blue=$Teams[$i+2];
			$totalred=$totalred+$red;
			$totalblue=$totalblue+$blue;
			echo "<tr>";
			echo "<td>".$competitors[$i]."</td>";
			echo "<td>".$red."</td>";
			echo "<td>".$competitors[$i+2]."</td>";
			echo "<td>".$blue."</td>";
			echo "</tr>";
		}
	}
	
	echo "<tr>";
	echo "</tr>";
	echo "<tr>";
	echo "<td>Total</td>";
	echo "<td>".$totalred."</td>";
	echo "<td>Total</td>";
	echo "<td>".$totalblue."</td>";
	echo "</tr>";
}

function GetFieldRanking($field,$team)
{
	$Q="SELECT avg(`".$field."`) FROM `".$_SESSION['datatable']."` WHERE Team='".$team."' AND Regional='".$_SESSION['regional']."'";
	$a=mysql_query($Q)or die(mysql_error());
	$value=0;
	$res=mysql_fetch_array($a);
	if($field=="Penalty")
	{
		$value=-$res['avg(`'.$field.'`)'];
	}
	else
	{
		$value=$res['avg(`'.$field.'`)'];
	}
	return $value;
}

function DisplayInputDataForm($fix)
{
	$columns=EnumerateColumnNames();
	$numteams=GetNumTeamsMatch();
	$numcols=count($columns);
	?>
    <h1>Input Data</h1>
    <form method="post" action "input.php">
    <table border="2">
    <?
	$eventid=Geteventid(GetDataTable());
	#$q1="SELECT * FROM eventvars WHERE type='width' AND eventid='" . $eventid . "'";
	$q2="SELECT * FROM eventvars WHERE eventid='" . $eventid . "'";
	$res1=mysql_query($q2) or die(mysql_error());
	while($row=mysql_fetch_array($res1))
	{
		$formwidth[$row['fieldname']] = $row['width'];
		$maxvals[$row['fieldname']] = $row['maxval'];
	}
	#$res2=mysql_query($q2) or die(mysql_error());
	#while($row=mysql_fetch_array($res1))
	#{
		#$maxvals[$row['fieldname']] = $row['variable'];
	#}
	for($i=1;$i<=$numteams+1;$i++)
	{
		if($i==1) { echo "<tr class='tableheader'>\n"; } else { echo "<tr>\n"; }
		for($j=1;$j<=$numcols;$j++)
		{
			if($i==1)
			{
				echo "<td>" . $columns[$j] . "</td>\n";
			}
			else
			{
				if($i!=2 & $j==1)
				{
					echo "<td></td>\n";
					continue;
				}
				$asdf=$formwidth[$columns[$j]]-5;
				if($fix)
				{
					echo "<td width=".($asdf)."><input type=\"text\" name=\"" . urlencode($columns[$j]) . "_" . ($i-1) . "\" style=\"width:" . $formwidth[$columns[$j]] . "px\" maxlength=\"" . $maxvals[$columns[$j]] . "\" value=\"" . $_POST[urlencode($columns[$j]) . '_' . ($i-1)] . "\" /></td>\n";
				}
				else if($asdf=="comments")
				{
			                echo "<td width=".($asdf)."><input type=\"text\" name=\"" . urlencode($columns[$j]) . "_" . ($i-1) . "\" style=\"width:" . $formwidth[$columns[$j]] . "px\" maxlength=\"" . $maxvals[$columns[$j]] . "\" /></td>\n";
				}
				else
				{
					echo "<td width=".($asdf)."><input type=\"text\" name=\"" . urlencode($columns[$j]) . "_" . ($i-1) . "\" style=\"width:" . $formwidth[$columns[$j]] . "px\" maxlength=\"" . $maxvals[$columns[$j]] . "\" value=\"0\" /></td>\n";
				}
                
			}
		}
		echo "</tr>";
		echo "    <input type=\"hidden\" value=\"" . $numteams . "\" name=\"teams\" />";
	}
	?>
    </table>
    <input type="hidden" value="sent" name="stage" />
    <input type="submit" name="Submit" value="Submit" />
    </form>
    <?
}

function DisplayNewInputDataForm()
{
	$columns=EnumerateColumnNames();
	$numteams=GetNumTeamsMatch();
	$numcols=count($columns);
	?>
    <h1>Input Data</h1><script type="text/javascript" src="./jsfunctions.js"></script>
    <form name="inputform" method="post" action "input.php">
    <table border="2">
    <?
	$eventid=Geteventid(GetDataTable());
	#$q1="SELECT * FROM eventvars WHERE type='width' AND eventid='" . $eventid . "'";
	$q2="SELECT * FROM eventvars WHERE eventid='" . $eventid . "'";
	$res1=mysql_query($q2) or die(mysql_error());
	while($row=mysql_fetch_array($res1))
	{
		$formwidth[$row['fieldname']] = $row['width'];
		$maxvals[$row['fieldname']] = $row['maxval'];
	}
	#$res2=mysql_query($q2) or die(mysql_error());
	#while($row=mysql_fetch_array($res1))
	#{
		#$maxvals[$row['fieldname']] = $row['variable'];
	#}
	for($i=1;$i<=4;$i++){
	if($i==1) { echo "<tr class='tableheader'>\n"; } else { echo "<tr>\n"; }
	for($j=1;$j<=$numcols;$j++)
	{
		if($i==1)
		{
			echo "<td>" . $columns[$j] . "</td>\n";
		}
		elseif($i==3)
		{
			echo "<td><input type=\"text\" id=\"".$columns[$j]."\" name=\"" . urlencode($columns[$j]) . "\" style=\"width: " . $formwidth[$columns[$j]] . "px;\" maxlength=\"" . $maxvals[$columns[$j]] . "\" /></td>\n";
		}
		elseif($i==2)
		{
			if($columns[$j]!="Comment"){
			#item up
			?><td><input type="button" name="increase" style="font-size:24px; height: 40px; width: <? echo $formwidth[$columns[$j]] ?>px;" value="+" onclick="modifyValue(this.form.elements['<? echo urlencode($columns[$j]) ?>'],this);" /></td>
<?
			}
			else
			{
				echo "<td></td>";
			}
		}
		elseif($i==4)
		{
			if($columns[$j]!="Comment"){
			#item down
			?><td><input type="button" name="decrease" style="font-size:24px; height: 40px; width: <? echo $formwidth[$columns[$j]] ?>px;" value="-" onclick="modifyValue(this.form.elements['<? echo urlencode($columns[$j]) ?>'],this);" /></td>
<?
			}
			else
			{
				echo "<td></td>";
			}
		}
	}
	echo "</tr>";
	}
	echo "    <input type=\"hidden\" value=\"1\" name=\"teams\" />";
	?>
    </table>
    <input type="hidden" value="sent" name="stage" />
    <input type="submit" name="Submit" value="Submit" />
    </form>
    <?
}

function mysql_fetch_fields($table) {
        // LIMIT 1 means to only read rows before row 1 (0-indexed)
        $result = mysql_query("SELECT * FROM `" . $table . "` LIMIT 1");
        $describe = mysql_query("SHOW COLUMNS FROM `" . $table . "`");
        $num = mysql_num_fields($result);
        $output = array();
        for ($i = 0; $i < $num; ++$i) {
                $field = mysql_fetch_field($result, $i);
                // Analyze 'extra' field
                $field->auto_increment = (strpos(mysql_result($describe, $i, 'Extra'), 'auto_increment') === FALSE ? 0 : 1);
                // Create the column_definition
                $field->definition = mysql_result($describe, $i, 'Type');
                if ($field->not_null && !$field->primary_key) $field->definition .= ' NOT NULL';
                if ($field->def) $field->definition .= " DEFAULT '" . mysql_real_escape_string($field->def) . "'";
                if ($field->auto_increment) $field->definition .= ' AUTO_INCREMENT';
                if ($key = mysql_result($describe, $i, 'Key')) {
                        if ($field->primary_key) $field->definition .= ' PRIMARY KEY';
                        else $field->definition .= ' UNIQUE KEY';
                }
                // Create the field length
                $field->len = mysql_field_len($result, $i);
                // Store the field into the output
                $output[$field->name] = $field;
        }
        return $output;
}

function GetDataTable()
{
#	echo "GetDataTable Return: '" . $_SESSION['datatable'] . "'";
	return $_SESSION['datatable'];
}

function GetDataTable_depreciated()
{
	$result=mysql_query("SELECT value FROM SpyderScoutingSettings WHERE name='datatable' LIMIT 1");
	$row=mysql_fetch_array($result);
	return $row[0];
}

function GetNumTeamsMatch()
{
	$eventtype = $_SESSION['competition'];
	if($eventtype=="VEX")
	{
		return 4;
	}
	if($eventtype=="FRC")
	{
		return 6;
	}
}

function GetNumTeamsMatch_depreciated()
{
	$result=mysql_query("SELECT value FROM SpyderScoutingSettings WHERE name='numteams' LIMIT 1");
	$row=mysql_fetch_array($result);
	return $row[0];
}

function Geteventid($datatable)
{
	$result=mysql_query("SELECT eventid FROM eventlist WHERE datatable='" . $datatable . "' AND event='" . $_SESSION['regional'] . "' LIMIT 1");
	$row=mysql_fetch_array($result);
	return $row[0];
}
//(1622);

function GetEventVars($eventid,$fieldname)
{
	$q=mysql_query("SELECT * FROM `eventvars` WHERE `eventid`=`" . $eventid . "` AND `fieldname`=`" . $fieldname . "`");
	$r=mysql_fetch_array($q);
	return $r;
}

function DisplayCharts($limit)
{
	?>
    <h1 align="center">Displaying Charts for <? echo $_SESSION['regional'] ?> Regional</h1>
    <?
	#DisplayChartsNew($limit, $field, $container, $title, $text);
	#DisplayChartsNew($limit,"Points Scored", "Points_scored_container","Average Team Points Scored","Points");
	#DisplayChartsNew($limit,"Autonomous", "Autonomous_container","Average Team Autonomous","Autonomous");
	#DisplayChartsNew($limit,"Penalty Points","Penalty_container","Average Team Penalties","Penalties");
	#DisplayChartsNew($limit,"","","","")
	$cols=EnumerateColumnNames();
	$numcols=count($cols);
	$eventid=GetEventid(GetDataTable());
	for($i=1;$i<=$numcols;$i++)
	{
		#determine whether or not the column needs to be charted
		$q="SELECT * FROM eventvars WHERE `eventid`='" . $eventid . "' AND `fieldname`='" . $cols[$i] . "'";
		#echo $q."---";
		$e=mysql_query($q) or die(mysql_error());
		#$r=GetEventVars($eventid,$cols[$i]);
		#$table=GetEventVars($eventid,$cols[$i]);
		$r=mysql_fetch_array($e);
		if($r['chart_chart']=='1')
		{
			DisplayChartsNew($limit,$cols[$i],$cols[$i]."container","Average Team " . $cols[$i],$cols[$i]);
		}
		#echo "chart_chart:".$r['chart_chart']." - ".$cols[$i];
		#echo "test\n";
	}
}

function DisplayChartsNew($limit, $field, $container, $title, $text)
{
	/**********************************
	**      $field CHART             **
	**********************************/
	?>
    <?
						#$limit=24;
						#$field="Penalty Points";
						$query="SELECT Team FROM teams WHERE Datatable='" . $_SESSION['datatable'] . "' AND Regional='".$_SESSION['regional']."'";
						$result1=mysql_query($query)or die("mysql error Query is: $query  error is: " . mysql_error());
						$num_rows=mysql_num_rows($result1);
						$i=1;
						while($row = mysql_fetch_array($result1)){
							${'team_'.$i}=$row['Team'];
							$i++;
							#echo $row['Team']."\n";
							}
	
						$values = array();
						$i=1;
								   
						while($i <= mysql_num_rows($result1)){
							$query="SELECT avg(`" . $field . "`) FROM `" . $_SESSION['datatable'] . "` WHERE team='".${'team_'.$i}."' AND regional='".$_SESSION['regional']."'";
							$result=mysql_query($query);
							if (!$result) {
die("I JUST GOT A BLEEDIN QUERY ERROR!!!!!<br />Query is: $query<br />Error is: ".mysql_error());
}				

							while($results = mysql_fetch_array($result))
							{
							#${'scored_'.$i}=round($row['avg(scored)'], 2);
							//echo round($results['avg(scored)'], 2) . ",";
							$temparray = array('team '.${'team_'.$i} => round($results['avg(`' . $field . '`)'], 2));
							$values = array_merge($values, $temparray);
							}
							
							$i++;
						}
						
						arsort($values);
						?>
    <!-- 1. Add these JavaScript inclusions in the head of your page -->
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
		<script type="text/javascript" src="js/highcharts.js"></script>
		
		<!-- 1a) Optional: add a theme file -->
		<!--
			<script type="text/javascript" src="./js/themes/gray.js"></script>
		-->
		
		<!-- 1b) Optional: the exporting module -->
		<script type="text/javascript" src="js/modules/exporting.js"></script>
		
		
		<!-- 2. Add the JavaScript to initialize the chart on document ready -->
		<script type="text/javascript">
		
			var chart;
			$(document).ready(function() {
				chart = new Highcharts.Chart({
					chart: {
						renderTo: '<?  echo $container ?>',
						defaultSeriesType: 'column',
						margin: [ 50, 50, 100, 80]
					},
					title: {
						text: '<? echo $title ?>'
					},
					xAxis: {
						categories: [
							<?
						$d=0;
						foreach($values as $key => $value) {
							if($d==$limit){break;}
							echo "'".$key."',";
							$d++;
						}
							?>
						],
						labels: {
							rotation: -45,
							align: 'right',
							style: {
								 font: 'normal 13px Verdana, sans-serif'
							}
						}
					},
					yAxis: {
						min: 0,
						title: {
							text: '<? echo $text ?>'
						}
					},
					legend: {
						enabled: false
					},
					tooltip: {
						formatter: function() {
							return '<b>'+ this.x +'</b><br/>'+
								 'Score: '+ Highcharts.numberFormat(this.y, 1);
						}
					},
				        series: [{
						name: '<? echo $text ?>',
						data: [
						<?
						$d=0;
						foreach($values as $key => $value) {
							if($d==$limit){break;}
							echo $value.',';
							$d++;
						}
							?>],
						dataLabels: {
							enabled: true,
							rotation: -90,
							color: '#FFFFFF',
							align: 'right',
							x: -3,
							y: 10,
							formatter: function() {
								return this.y;
							},
							style: {
								font: 'normal 13px Verdana, sans-serif'
							}
						}			
					}]
				});
				
				
			});
		</script>
    <div id="<?  echo $container ?>" style="width: 100%; height: 400px"></div>
    <?
}

function DisplayChartsMatch($limit, $field, $container, $title, $text,$yaxis,$match)
{
	/**********************************
	**      $field CHART             **
	**********************************/
	?>
    <?
					for($a=1;$a<=$limit;$a++)
					{
						#$limit=24;
						#$field="Penalty Points";
						$query="SELECT Team FROM teams WHERE Datatable='" . $_SESSION['datatable'] . "' AND Regional='".$_SESSION['regional']."'";
						$result1=mysql_query($query)or die("mysql error Query is: $query  error is: " . mysql_error());
						#echo "initquery success!";
						$num_rows=mysql_num_rows($result1);
						$i=1;
						while($row = mysql_fetch_array($result1)){
							${'team_'.$i}=$row['Team'];
							$i++;
							#echo $row['Team']."\n";
							}
	
						${'values'.$a} = array();
						$i=1;
								   
						while($i <= mysql_num_rows($result1)){
							$query="SELECT * FROM `" . $_SESSION['datatable'] . "` WHERE `Team`='".${'team_'.$i}."' AND `Regional`='".$_SESSION['regional']."' AND `Match`='" . $match . "'";
							$result=mysql_query($query)or die(mysql_error());
							if (!$result) {
die("I JUST GOT A BLEEDIN QUERY ERROR!!!!!<br />Query is: $query<br />Error is: ".mysql_error());
}				

							while($results = mysql_fetch_array($result))
							{
								#print_r($results);
								#echo "Test!";
							#${'scored_'.$i}=round($row['avg(scored)'], 2);
							//echo round($results['avg(scored)'], 2) . ",";
							$temparray = array('team '.${'team_'.$i} => round($results[$field[$a-1]], 2));
							${'values'.$a} = array_merge(${'values'.$a}, $temparray);
							}
							
							$i++;
						}
						
						#arsort(${'values'.$a});
						#print_r(${'values'.$a});
					}
						?>
    <!-- 1. Add these JavaScript inclusions in the head of your page -->
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
		<script type="text/javascript" src="js/highcharts.js"></script>
		
		<!-- 1a) Optional: add a theme file -->
		<!--
			<script type="text/javascript" src="./js/themes/gray.js"></script>
		-->
		
		<!-- 1b) Optional: the exporting module -->
		<script type="text/javascript" src="js/modules/exporting.js"></script>
		
		
		<!-- 2. Add the JavaScript to initialize the chart on document ready -->
		<script type="text/javascript">
		
			var chart;
			$(document).ready(function() {
				chart = new Highcharts.Chart({
					chart: {
						renderTo: '<?  echo $container ?>',
						defaultSeriesType: 'column',
						margin: [ 50, 100, 100, 80]
					},
					title: {
						text: '<? echo $title ?>'
					},
					xAxis: {
						categories: [
							<?
						$d=0;
						foreach(${'values'.'1'} as $key => $value) {
							#if($d==$limit){break;}
							echo "'".$key."',";
							$d++;
						}
							?>
						],
						labels: {
							rotation: -45,
							align: 'right',
							style: {
								 font: 'normal 13px Verdana, sans-serif'
							}
						}
					},
					yAxis: {
						min: 0,
						title: {
							text: '<? echo $yaxis ?>'
						}
					},
					legend: {
						enabled: false
					},
					tooltip: {
						formatter: function() {
							return '<b>'+ this.x +'</b><br/>'+
								 'Points: '+ Highcharts.numberFormat(this.y, 1);
						}
					},
					legend: {
			         layout: 'vertical',
			         align: 'right',
			         verticalAlign: 'top',
			         x: 8,
			         y: 100,
			         borderWidth: 2
			      },
				        series: [<?
						for($a=1;$a<$limit;$a++){
						?>{
						name: '<? echo $text[$a-1] ?>',
						data: [<?
						$d=0;
						foreach(${'values'.$a} as $key => $value) {
							echo $value.',';
							$d++;
						}
							?>]
						},<? }?>]
				});
			});
		</script><br />
    <div id="<?  echo $container ?>" style="width: 100%; height: 400px"></div>
    <?
}

function DisplayChartsTeam($limit, $field, $container, $title, $text,$text2,$team)
{
	/**********************************
	**      $field CHART             **
	**********************************/
	?>
    <?
					for($a=1;$a<=$limit;$a++)
					{
						#$limit=24;
						#$field="Penalty Points";
						$query="SELECT * FROM `".$_SESSION['datatable']."` WHERE `Regional`='".$_SESSION['regional']."' AND `Team`='".$team."'";
						#echo $query;
						$result1=mysql_query($query)or die("mysql error Query is: $query  error is: " . mysql_error());
						#echo "initquery success!";
						#$num_rows=mysql_num_rows($result1);
						$i=1;
						#echo $num_rows;
						while($row = mysql_fetch_array($result1)){
							#print_r($row);
							${'team_'.$i}=$row['Match'];
							$i++;
							#echo $row['Match']."\n";
							}
	
						${'values'.$a} = array();
						$i=1;
						
						while($i <= mysql_num_rows($result1)){
							$match=${'team_'.$i};
							$query="SELECT * FROM `" . $_SESSION['datatable'] . "` WHERE `Team`='".$team."' AND `Regional`='".$_SESSION['regional']."' AND `Match`='" . $match . "'";
							#echo $query;
							$result=mysql_query($query)or die(mysql_error());
							if (!$result) {
die("I JUST GOT A BLEEDIN QUERY ERROR!!!!!<br />Query is: $query<br />Error is: ".mysql_error());
}				

							while($results = mysql_fetch_array($result))
							{
								#print_r($results);
								#echo "Test!";
							#${'scored_'.$i}=round($row['avg(scored)'], 2);
							//echo round($results['avg(scored)'], 2) . ",";
							$temparray = array('Match '.${'team_'.$i} => round($results[$field[$a-1]], 2));
							${'values'.$a} = array_merge(${'values'.$a}, $temparray);
							}
							
							$i++;
						}
						
						#arsort(${'values'.$a});
						#print_r(${'values'.$a});
					}
						?>
    <!-- 1. Add these JavaScript inclusions in the head of your page -->
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
		<script type="text/javascript" src="js/highcharts.js"></script>
		
		<!-- 1a) Optional: add a theme file -->
		<!--
			<script type="text/javascript" src="./js/themes/gray.js"></script>
		-->
		
		<!-- 1b) Optional: the exporting module -->
		<script type="text/javascript" src="js/modules/exporting.js"></script>
		
		
		<!-- 2. Add the JavaScript to initialize the chart on document ready -->
		<script type="text/javascript">
		
			var chart;
			$(document).ready(function() {
				chart = new Highcharts.Chart({
					chart: {
						renderTo: '<?  echo $container ?>',
						defaultSeriesType: 'column',
						margin: [ 50, 100, 100, 80]
					},
					title: {
						text: '<? echo $title ?>'
					},
					xAxis: {
						categories: [<?
						$d=0;
						foreach(${'values'.'1'} as $key => $value) {
							#if($d==$limit){break;}
							echo "'".$key."',";
							$d++;
						}
							?>],
						labels: {
							rotation: -45,
							align: 'right',
							style: {
								 font: 'normal 13px Verdana, sans-serif'
							}
						}
					},
					yAxis: {
						min: 0,
						title: {
							text: '<? echo $yaxis ?>'
						}
					},
					legend: {
						enabled: false
					},
					tooltip: {
						formatter: function() {
							return '<b>'+ this.x +'</b><br/>'+
								 'Points: '+ Highcharts.numberFormat(this.y, 1);
						}
					},
				  legend: {
			         layout: 'vertical',
			         align: 'right',
			         verticalAlign: 'top',
			         x: 8,
			         y: 100,
			         borderWidth: 2
			      },
				        series: [<?
						for($a=1;$a<$limit;$a++){
						?>{
						name: '<? echo $text[$a-1] ?>',
						data: [<?
						$d=0;
						foreach(${'values'.$a} as $key => $value) {
							echo $value.',';
							$d++;
						}
							?>]
						},<? }?>]
				});
			});
		</script><br />
    <div id="<?  echo $container ?>" style="width: 100%; height: 400px"></div>
    <?
}

?>
